from fastapi import APIRouter
from scheduler import scheduler
from sync import perform_sync

router = APIRouter()


@router.post("/import/start")
def start_import():
    perform_sync()


@router.post("/sync/start")
def start_sync():
    if not scheduler.get_job("products_sync"):
        scheduler.add_job(perform_sync, 'interval', minutes=60, id="products_sync")
        scheduler.start()
        return {"message": "同步任务已启动"}
    return {"message": "同步任务已存在"}


@router.post("/sync/stop")
def stop_sync():
    scheduler.remove_job("products_sync")
    return {"message": "同步任务已停止"}


@router.post("/sync/run-once")
def run_once():
    perform_sync()
    return {"message": "已手动执行同步任务"}


@router.get("/sync/status")
def get_status():
    from pymongo import MongoClient
    from config import MONGO_URI, MONGO_DB_NAME, SYNC_META_ID
    db = MongoClient(MONGO_URI)[MONGO_DB_NAME]
    status = db['sync_metadata'].find_one({"_id": SYNC_META_ID})
    return status
